<?php
namespace Api\Controller;
use Think\Controller;
class MyCardController extends CommonController {
    //查询我已经申请的店铺会员卡
    public function index(){
        if($_GET['openid']){
            $map['m.openid'] = $_GET['openid'];
        }
        if(intval($_GET['shop_id'])){
            $map['m.shop_id'] = $_GET['shop_id'];
        }
        $map['m.wid'] = session('wid');
        $map['m.status'] = 1;
        $map['c.status'] = 1;
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $shopid = M("Shop")->where($eq)->getField("shop_id");
        //查询我的会员卡
        $list['mine'] = M('shop_mycard')->alias('m')
            ->join("tp_shop_card c on c.id=m.card_id")
            ->join("tp_shop s on s.shop_id=m.shop_id")
            ->field("m.*,c.title,c.pic,c.level_name,s.name,s.logo_url")
            ->where($map)
            ->order("id desc")
            ->select();
        //查询所有的会员卡
        //var_dump(intval($_GET['shop_id']));exit();
        if(intval($_GET['shop_id'])){
            $sql = "select c.*,s.name,s.logo_url from tp_shop_card c INNER JOIN tp_shop as s ON c.shop_id=s.shop_id where c.id not in
                (SELECT card_id from tp_shop_mycard where openid ='".I('openid')."' and wid =".session('wid')." and status=1)
                and c.status =1 and c.shop_id='".$_GET['shop_id']."' and c.wid= " .session('wid');
            $query = "select count(*) as count from tp_shop_card  where id not in
                (SELECT card_id from tp_shop_mycard where openid ='".I('openid')."' and wid =".session('wid').")
                and status =1 and shop_id= '".$_GET['shop_id']."' and wid= " .session('wid');
        }else{
            $sql = "select c.*,s.name,s.logo_url from tp_shop_card c INNER JOIN tp_shop as s ON c.shop_id=s.shop_id where c.id not in
                (SELECT card_id from tp_shop_mycard where openid ='".I('openid')."' and wid =".session('wid')." and status=1)
                and c.status =1 and c.shop_id!= '".$shopid."' and c.wid= " .session('wid');
            $query = "select count(*) as count from tp_shop_card  where id not in
                (SELECT card_id from tp_shop_mycard where openid ='".I('openid')."' and wid =".session('wid').")
                and status =1 and shop_id!= '".$shopid."' and wid= " .session('wid');
        }


        $list['other'] = M()->query($sql);
        $list['count'] = M()->query($query);
        $this->ajaxReturn($list);
    }

    //获取会员卡的相关信息
    public function getCard(){
        $map['c.wid'] = session('wid');
        $map['c.status'] = 1;
        $map['c.id'] = $_GET['card_id'];
        //查询我的会员卡
        $list['mine'] = M('shop_card')->alias('c')
            ->join("tp_shop s on s.shop_id=c.shop_id")
            ->field("c.*,s.name,s.logo_url")
            ->where($map)
            ->order("id desc")
            ->find();
        //查询该会员卡的会员特权
        $eq['wid'] = session('wid');
        $eq['status'] = 1;
        $eq['card_id'] = $_GET['card_id'];
        $list['rights'] = M('shop_card_rights')->where($eq)->select();
        //获取会员的特价表单
        $list['form'] = $this->getEditForm();
        $this->ajaxReturn($list);

    }
    //获取申请页面的表单
    // 获取商品编辑表单
    private function getEditForm(){

        $res['add_url'] = "https://www.58zltc.com/api.php/MyCard/addMyCard";
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'text', 'title'=>'手机号', 'name'=>'phone');
        $form[] = array('type'=>'text', 'title'=>'姓名', 'name'=>'name');
        $res['form'] = $form;
        $res['index_url'] = "/pages/mine/shop/mycard/cardlist";
        return $res;
    }
    //添加我申请的会员卡
    public function addMyCard(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        $mp['wid'] = session('wid');
        $mp['id'] = $_POST['card_id'];
        $card = M("shop_card")->where($mp)->find();//卡片的店铺id
        //限制开通一张会员卡
        $card2 = M('shop_mycard')->where(['shop_id'=>$card['shop_id'],'openid'=>$_POST['openid']])->find();
        if($card2){
            $arr = array("err_code" => 400, "err_msg" => "您已开通！");
            $this->ajaxReturn($arr);
        }


        $_POST['shop_id'] = $card['shop_id'];
        $_POST['wid'] = session('wid');
        $_POST['create_time'] = date("Y-m-d H:i:s");
        $_POST['status'] = 1;

        if(M("shop_mycard")->add($_POST)){
            //会员卡添加成功，查询有没有关联会员卡，如有关联，直接添加改关联会员卡
           if(!empty($card['linkshop'])){
               $shops = explode(',',$card['linkshop']);
               foreach($shops as $shop){
                   $linkmycard = M('shop_mycard')->where(array('card_id'=>$shop,'status'=>1,'openid'=>$_POST['openid']))->find();//查找是否已经申请了该会员卡
                   if(empty($linkmycard)){
                       //查询该会员的卡片信息
                       $linkcard = M('shop_card')->where(array('id'=>$shop,'status'=>1))->find();//查找该会员卡是否正常运行
                       if($linkcard){
                           //如果没申请该会员卡，申请该关联会员卡
                           $_POST['shop_id'] = $linkcard['shop_id'];
                           $_POST['card_id'] = $shop;
                           M("shop_mycard")->add($_POST);
                       }
                   }
               }
           }
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //获取会员的申请的会员卡详情
    public function myCard(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['id'] = $_GET['card_id'];
        //查询会员卡的详情
        $list['mycard'] = M('shop_mycard')->where($eq)->find();
        //查询会员卡的详情
        $map['c.wid'] = session('wid');
        $map['c.status'] = 1;
        $map['c.id'] = $list['mycard']['card_id'];
        $list['card'] = M('shop_card')->alias('c')
            ->join("tp_shop s on s.shop_id=c.shop_id")
            ->field("c.*,s.name,s.logo_url")
            ->where($map)
            ->order("id desc")
            ->find();
        //查询优惠券的数量
        $list['count'] = M('Shop_coupon_log')->where(array('wid'=>session('wid'),'mycard_id'=>$_GET['card_id']))->count('id');
        $this->ajaxReturn($list);
    }

    //查询我选择会卡的充值套餐以及充值金额的表单
    public function getRecharge(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['id'] = $_GET['card_id'];
        //查询会员卡的详情
        $list['mycard'] = M('shop_mycard')->where($eq)->find();
        //获取选择会员卡的充值优惠记录
        $map['wid'] = session('wid');
        $map['card_id'] = $list['mycard']['card_id'];
        $map['status'] = 1;
        $list['recharge'] = M('shop_card_recharge')->where($map)->select();
    //获取充值的表单
        $res['add_url'] = "https://www.58zltc.com/api.php/MyCard/addrecharge";
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'digit', 'title' => '充值金额', 'name' => 'money');
        $form[] = array('type' => 'top');
        $res['form'] = $form;
        $res['index_url'] = "/pages/mine/shop/card/card";
        $list['form'] = $res;
        $this->ajaxReturn($list);
    }
    //充值会员卡
    public function recharge(){
        $eq['wid'] = session('wid');
        $wechat = M("Wechat")->where($eq)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $_POST['wid'] = session('wid');
        $eq['id'] = $_POST['mycard_id'];

        //查找申请的盖会员卡
        $mycard = M('shop_mycard')->where($eq)->find();
        $_POST['shop_id'] = $mycard['shop_id'];
        //获取充值金额
        $money = $_POST['money'];
        //获取充值套餐
        if(!$money){
            //充值金额为空，查找充值套餐的记录
            $recharge = M('shop_card_recharge')->where(array('id'=>$_POST['recharge_id']))->find();
            $_POST['money'] = $recharge['money'];
            $_POST['get_money'] = $recharge['get_money'];
        }else{
            //充值金额不为空，需要查询小于该充值金额最小的奖励记录
            $map['money']= array('elt',$money);
            $map['wid'] = session('wid');
            $map['card_id'] = $mycard['card_id'];
            $recharge =M('shop_card_recharge')->where($map)->find();
            $_POST['get_money'] = $recharge['get_money'];
        }
        $_POST['out_trade_no'] = $this->build_order_no();
        $_POST['create_time'] = date("Y-m-d H:i:s");
        //添加充值记录
        if (!M("shop_recharge_log")->add($_POST)) {
            $arr = array("err_code" => 400, "err_msg" => "网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        //支付
        $url = "https://" . $_SERVER['HTTP_HOST'] . U("Notify/cardRecharge");
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
         $data['remark'] = "智联同城";
        $input->SetBody($data['remark']);
        $input->SetAttach('会员卡充值');
        $input->SetOut_trade_no($_POST['out_trade_no']);
        $input->SetTotal_fee(($_POST['money'] * 100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try {
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage() . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if ($wxorder['return_code'] == "FAIL") {
            $arr = array("err_code" => 400, "err_msg" => $wxorder['return_msg'] . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try {
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;


    }
    //充值次数套餐
    public function getMeal(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['id'] = $_GET['card_id'];
        //查询会员卡的详情
        $list['mycard'] = M('shop_mycard')->where($eq)->find();
        //获取选择会员卡的充值优惠记录
        $map['wid'] = session('wid');
        $map['card_id'] = $list['mycard']['card_id'];
        $map['status'] = 1;
        $list['meal'] = M('shop_card_meal')->where($map)->select();
            foreach($list['meal'] as $k=>$meal){
                $goodid_arr = explode(',',$meal['goods_id']);
                $list['meal'][$k]['good'] = M('shop_card_good')->where(array('id'=>array('in',$meal['goods_id']),'status'=>1))->select();

            }
        $this->ajaxReturn($list);

    }
    //充值次数订单
    public function meal(){
        $eq['wid'] = session('wid');
        $wechat = M("Wechat")->where($eq)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $eq['openid'] = $_POST['openid'];
        $_POST['wid'] = session('wid');
        $eq['id'] = $_POST['mycard_id'];

        //查找申请的盖会员卡
        $mycard = M('shop_mycard')->where($eq)->find();
        $_POST['shop_id'] = $mycard['shop_id'];
        //获取充值金额
        //获取充次套餐
        $meal = M('shop_card_meal')->where(array('id'=>$_POST['meal_id']))->find();
        $_POST['money'] = $meal['user_price'];

        $_POST['out_trade_no'] = $this->build_order_no();
        $_POST['create_time'] = date("Y-m-d H:i:s");
        $_POST['pay_money'] = $meal['pay_money'];

        //添加充值记录
        if (!M("shop_meal_log")->add($_POST)) {
            $arr = array("err_code" => 400, "err_msg" => "网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        $mealLogId = M('shop_meal_log')->getLastInsID();
        //获取套餐商品的详情
        $goodid_arr = explode(',',$meal['goods_id']);

        foreach($goodid_arr as $goodid){
            $good = M('shop_card_good')->where(array('id'=>$goodid))->find();
            $add['wid'] = $good['wid'];
            $add['shop_id'] = $good['shop_id'];
            $add['title'] = $good['title'];
            $add['card_good_id'] = $good['id'];//服务商品id
            $add['create_time'] = date("Y-m-d H:i:s");
            $add['meallog_id'] = $mealLogId;
            $add['num'] = $good['num'];
            $add['openid'] = $_POST['openid'];
            $add['img_url'] = $good['img_url'];
            M('shop_meal_log_good')->add($add);
            unset($add);
        }


        //支付
        $url = "https://" . $_SERVER['HTTP_HOST'] . U("Notify/cardMeal");
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $data['remark'] = "智联同城";
        $input->SetBody($data['remark']);
        $input->SetAttach('会员卡充次');
        $input->SetOut_trade_no($_POST['out_trade_no']);
        $input->SetTotal_fee(($_POST['money'] * 100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try {
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage() . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if ($wxorder['return_code'] == "FAIL") {
            $arr = array("err_code" => 400, "err_msg" => $wxorder['return_msg'] . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try {
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
    }
    //获取充值记录
    public function getRchargeLog(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['mycard_id'] = $_GET['mycard_id'];
        $eq['type'] = $_GET['type'];
        $eq['state'] = 1;
        $list['log'] = M('shop_recharge_log')->where($eq)->select();
        $list['count'] = M('shop_recharge_log')->where($eq)->sum('money');
        $list['count1'] = M('shop_recharge_log')->where($eq)->sum('get_money');
        $this->ajaxReturn($list);
    }
    //查询购买的次数套餐
    public function getMealLog(){
        $eq['l.wid'] = session('wid');
        $eq['l.openid'] = $_GET['openid'];
        $eq['l.mycard_id'] = $_GET['mycard_id'];
        $eq['l.state'] = 1;//支付成功
        $list['log'] = M('shop_meal_log')
            ->field('l.*,m.title')
            ->alias('l')
            ->join('tp_shop_card_meal m on m.id=l.meal_id')
            ->where($eq)->select();
        //查询改套餐的服务商品
        foreach($list['log'] as $k=>$log){
            $list['log'][$k]['goods'] = M('shop_meal_log_good')->where(array('meallog_id'=>$log['id']))->select();
        }
        $this->ajaxReturn($list);
    }
    //获取积分记录
    public function getIntegralLog(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['mycard_id'] = $_GET['mycard_id'];

        $list['log'] = M('shop_integral_log')->where($eq)->select();
        $list['count'] = M('shop_integral_log')->where($eq)->sum('integral');

        $this->ajaxReturn($list);
    }
    //判断扫码用户是否是商家扫描
    public function payRight(){
        $eq['wid'] = session('wid');
        $eq['id'] = $_GET['card_id'];
        $mycard = M('shop_mycard')->where($eq)->find();
        //根据我的会员卡信息去查询二维码标识记录
        $map['wid'] = session('wid');
        $map['openid'] = $mycard['openid'];
        $map['mycard_id'] = $_GET['card_id'];
        $qrcode = M('Shop_qrcode')->where($map)->order('id desc')->find();

        if($qrcode['num'] != $_GET['num']){
           // $arr = array("err_code" => 400, "err_msg" => '二维码已过期');
            //$this->ajaxReturn($arr);
        }
        //查询扫码人的信息
        $user = M('Member')->where(array('openid'=>$_GET['openid']))->find();
        if($user['shop_id'] != $mycard['shop_id']){
            $arr = array("err_code" => 400, "err_msg" => '您没有扫码权限');
            $this->ajaxReturn($arr);
        }
        $arr = array("err_code" => 1, "err_msg" => '扫码成功');
        $this->ajaxReturn($arr);
    }
    //支付类型
    public function payType(){
        $eq['wid'] = session('wid');
        $eq['id'] = $_GET['card_id'];
        $type = $_GET['type'];
        if($type == 1){
            //查询商店log
            $user = M('Member')->where(array('openid'=>$_GET['openid']))->find();
            $shop = M('Shop')->where(array('shop_id'=>$user['shop_id']))->find();
            $res['add_url'] = "https://www.58zltc.com/api.php/MyCard/pay";
            $form[] = array('type' => 'top');
            $form[] = array('type' => 'digit', 'title' => '支付金额', 'name' => 'money');
            $form[] = array('type' => 'top');
            $res['form'] = $form;
            $res['index_url'] = "/pages/mine/shop/card/card";
            $list['form'] = $res;


            //金额支付
            $list['list'] =$shop;


        }elseif($type == 2){
            $user = M('Member')->where(array('openid'=>$_GET['openid']))->find();
            $shop = M('Shop')->where(array('shop_id'=>$user['shop_id']))->find();
            //套餐支付，查询套餐
            $mycard = M('Shop_mycard')->where($eq)->find();
            //查询套餐
            $map['l.wid'] = session('wid');
            $map['l.mycard_id'] = $mycard['id'];
            $map['l.state'] = 1;
            $meals = M('Shop_meal_log')
                ->field('l.*,m.title,m.user_price')
                ->alias('l')
                ->join('tp_shop_card_meal as m on m.id=l.meal_id')
                ->where($map)->select();

            foreach($meals as $k=>$meal){
                $meals[$k]['goods'] = M('Shop_meal_log_good')->where(array('wid'=>session('wid'),'meallog_id'=>$meal['id']))->select();

            }
            $list['list'] = $meals;


            $res['add_url'] = "https://www.58zltc.com/api.php/MyCard/pay";
            $form[] = array('type' => 'top');

            $res['form'] = $form;
            $res['index_url'] = "/pages/mine/shop/card/card";
            $res['shop'] = $shop;
            $list['form'] = $res;

        }
        $this->ajaxReturn($list);
    }
    //支付
    public function pay(){
        $eq['wid'] = session('wid');
        $eq['id'] = $_POST['card_id'];
        //查询我的会员卡数据库
        $mycard = M('Shop_mycard')->where($eq)->find();
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        M()->startTrans();
        if($_POST['type'] == 1){
            //金额支付，先支付奖励的金额不进入店铺钱包，扣除的充值金额进入店铺钱包
            if($_POST['money'] > $mycard['money']){
                $arr = array("err_code" => 400, "err_msg" => "账户余额不足！");
                $this->ajaxReturn($arr);
            }
            //判断账户是否还有赠送金额
            if($mycard['get_money'] > 0){
                //支付金额大于赠送金额
                if($_POST['money'] >= $mycard['get_money']){
                    //扣除赠送金额,会员账户扣除金额
                    $change['get_money'] = 0;
                    $change['money'] = $mycard['money'] - $_POST['money'];
                   $r[] = M('Shop_mycard')->where($eq)->save($change);
                    unset($change);
                    $getMoney = $_POST['money']- $mycard['get_money'];
                    $deduction = $mycard['get_money'];
                }else{
                    //支付金额小于赠送金额
                    $change['get_money'] =  $mycard['get_money'] - $_POST['money'];
                    $change['money'] = $mycard['money'] - $_POST['money'];
                   $r[] = M('Shop_mycard')->where($eq)->save($change);
                    unset($change);
                    $getMoney = 0;
                    $deduction = $_POST['money'];
                }
            }else{
                //增送金额为0
                $change['money'] = $mycard['money'] - $_POST['money'];
                $r[] = M('Shop_mycard')->where($eq)->save($change);
                $getMoney = $_POST['money'];
                $deduction = 0;
            }

            //增加会员金额支出
            $data['wid'] = session('wid');
            $data['mycard_id'] = $_POST['card_id'];
            $data['shop_id'] = $mycard['shop_id'];
            $data['openid']  = $mycard['openid'];
            $data['money'] = $_POST['money'];
            $data['state'] = 1;
            $data['out_trade_no'] = $this->build_order_no();
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['change_openid'] = $_POST['openid'];
            $data['type'] = 2;//支付
            $r[] = M("shop_recharge_log")->add($data);

            //商户获得金额
            $shop_order['wid'] = session('wid');
            $shop_order['shop_id'] = $mycard['shop_id'];
            $shop_order['openid'] = $mycard['openid'];
            $shop_order['out_trade_no'] = $data['out_trade_no'];
            $shop_order['type'] = 'qrcode';
            $shop_order['all_money'] = $getMoney;
            $shop_order['last_time'] = date("Y-m-d H:i:s");
            $shop_order['remark'] = '线下核销，支付'.$_POST['money'].'赠送抵扣'.$deduction;
            $r[] = M('Validate_log')->add($shop_order);
            unset($data);
            //消费增加积分

            $card = M('shop_card')->where(array('id'=>$mycard['card_id']))->find();
            //获得积分
            $getCredit = $_POST['money'] * $card['credit'];
            $data['wid'] = session('wid');
            //$data['rechargelog_id'] = $log['id'];
            $data['mycard_id'] = $_POST['card_id'];
            $data['shop_id'] = $mycard['shop_id'];
            $data['openid'] = $mycard['openid'];
            $data['integral'] = $getCredit;
            $data['remark'] = '会员消费'.$_POST['money'].'获得积分';
            $data['create_time'] = date("Y-m-d H:i:s");
            //添加积分记录
            M('shop_integral_log')->add($data);
            M('shop_mycard')->where(array('id'=>$_POST['card_id']))->setInc('integral',$getCredit);

        }else{
            //按次扣费
            //更具充值的套餐商品
            $map['wid'] = session('wid');
            $map['id'] = $_POST['meal_log_good'];
            $meal_good = M('Shop_meal_log_good')->where($map)->find();
            //查找充值的套餐记录
            $where['wid'] = session('wid');
            $where['id'] = $meal_good['meallog_id'];
            $meal = M('Shop_meal_log')->where($where)->find();
            if($meal_good['num'] - $meal_good['days'] <= 0){
                $arr = array("err_code" => 400, "err_msg" => "该商品次数不足！");
                $this->ajaxReturn($arr);
            }
            //扣除次数
            //$r[] =  M('Shop_meal_log_good')->where($map)->setDec('num',1);
            $r[] =  M('Shop_meal_log_good')->where($map)->setInc('days',1);

            $data['wid'] = session('wid');
            $data['meal_good_id'] = $_POST['meal_log_good'];//支付套餐商品id
            $data['mycard_id'] = $_POST['card_id'];
            $data['shop_id'] = $mycard['shop_id'];
            $data['openid']  = $mycard['openid'];
            $data['money'] = $meal['pay_money'];
            $data['state'] = 1;
            $data['out_trade_no'] = $this->build_order_no();
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['change_openid'] = $_POST['openid'];
            $data['mymeal_id'] = $meal['meal_id'];
            $data['remark'] = '核销'.$meal_good['title'].'一次';
            $r[] = M('Shop_meal_pay_log')->add($data);

            //商户获得金额
            $shop_order['wid'] = session('wid');
            $shop_order['shop_id'] = $mycard['shop_id'];
            $shop_order['openid'] = $mycard['openid'];
            $shop_order['out_trade_no'] = $data['out_trade_no'];
            $shop_order['type'] = 'qrcode';
            $shop_order['all_money'] = $meal['pay_money'];
            $shop_order['last_time'] = date("Y-m-d H:i:s");
            $shop_order['remark'] = '线下核销，套餐支付'.$meal_good['title'];
            $r[] = M('Validate_log')->add($shop_order);

            $card = M('shop_card')->where(array('id'=>$mycard['card_id']))->find();
            //获得积分
            $getCredit = $meal['pay_money'] * $card['credit'];
            $data['wid'] = session('wid');
            //$data['rechargelog_id'] = $log['id'];
            $data['mycard_id'] = $_POST['card_id'];
            $data['shop_id'] = $mycard['shop_id'];
            $data['openid'] = $mycard['openid'];
            $data['integral'] = $getCredit;
            $data['remark'] = '会员消费套餐'.$meal['pay_money'].'获得积分';
            $data['create_time'] = date("Y-m-d H:i:s");
            //添加积分记录
            M('shop_integral_log')->add($data);
            M('shop_mycard')->where(array('id'=>$_POST['card_id']))->setInc('integral',$getCredit);
        }
        if(in_array(false,$r)){
            M()->rollback();

            $arr = array("err_code" => 400, "err_msg" => "支付失败！");
            $this->ajaxReturn($arr);
        }else{
            M()->commit();
            //用户支付成功，接受到通知
            sendQrcodeMessage($mycard['openid'],$data['out_trade_no'],session('wid'));
            //成功商户接受到通知
            $arr = array("err_code" => 0, "err_msg" => "支付成功！");
            $this->ajaxReturn($arr);
        }
    }
    //查找会员的次数套餐消费记录
    public function getMealPayLog(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['mycard_id'] = $_GET['mycard_id'];

        $list['log'] = M('shop_meal_pay_log')->where($eq)->select();

        $this->ajaxReturn($list);
    }
    //查找会员专属优惠券
    public function getUserCoupon(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $map['card_id'] = M("Shop_mycard")->where(array('id'=>$_GET['card_id']))->getField("card_id");
        $list = M("shop_card_coupon")->where($map)->order("create_time desc")->select();
        foreach ($list as $key => $value) {
            $list[$key]['buy_percent'] = round(($value['buy_num']/$value['stock'])*100,2);
        }
        $this->ajaxReturn($list);
    }
    // 领取优惠券方法
    public function getCoupon(){
        $model = M("Shop_coupon_log");
        $new['wid'] = session('wid');
        $new['coupon_id'] = I("coupon_id");
        $new['openid'] = I("openid");
        $new['mycard_id'] = I("mycard_id");

        if($model->where($new)->find()){
            $arr = array("err_code"=>400,"err_msg"=>"你已经领取过了！");
            $this->ajaxReturn($arr);
        }

        $eq['id'] = I("coupon_id");
        $coupon = M("Shop_card_coupon")->where($eq)->find();
        if($coupon['buy_num'] >= $coupon['stock']){
            $arr = array("err_code"=>400,"err_msg"=>"优惠券已经被抢光了！");
            $this->ajaxReturn($arr);
        }
        $new['shop_id'] = $coupon['shop_id'];
        $new['title'] = $coupon['title'];
        $new['coupon_price'] = $coupon['coupon_price'];
        $new['coupon_remark'] = $coupon['coupon_remark'];
        $new['content'] = $coupon['content'];
        $new['img_url'] = $coupon['img_url'];
        $new['pics'] = $coupon['pics'];
        $new['create_time'] = date("Y-m-d H:i:s");
        $new['mycard_id'] = I("mycard_id");

        //领取优惠券需要修改buy_num
        $a = M('Shop_card_coupon')->where(['id'=>I("coupon_id")])->setInc('buy_num');
        if($model->add($new) && $a){
            $arr = array("err_code"=>0,"err_msg"=>"领取成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    /*
     * 店铺是否有会员卡
     *
     * */
    public function haveShopVipCard () {
        $id = I('shop_id');
        $row = M('shop_card')->where(['shop_id' => $id])->find();
        $row ? $this->ajaxReturn($row) : $this->ajaxReturn(0);
    }

    //查询会员卡关联
    public function getlinkcard(){
        $myCarid = I('id');
        $eq['id'] = $myCarid;
        $eq['wid'] = session('wid');
        $mycard = M('shop_mycard')->where($eq)->find();
        //获取的哦卡片id
        $card = M('shop_card')->where(array('id'=>$mycard['card_id']))->find();
        $list['list'] = array();
        if(!empty($card['linkshop'])){

            $map['c.wid'] = session('wid');
            $map['c.id'] = array('in',$card['linkshop']);
            $map['c.status'] = 1;

            $list['list'] = M('Shop_card')
                ->field('c.*,s.logo_url,s.name')
                ->alias('c')
                ->join('tp_shop as s on c.shop_id=s.shop_id')
                ->where($map)->select();
        }

        $list['count'] = count($list['list']);
        $this->ajaxReturn($list);
    }

    //查询推广奖励
    public function getRecommend(){
        $myCarid = I('card_id');
        $eq['id'] = $myCarid;
        $eq['wid'] = session('wid');
        $mycard = M('shop_mycard')->where($eq)->find();
        //查询该卡片的额推广奖励
        $card = M('shop_card')->where(array('id'=>$mycard['card_id']))->find();
        $list['recommendpay'] = 0;
        $list['recommendmeal'] = 0;
        $list['pay'] = 0;
        $list['meal'] = array();
        if($card['recommend'] > 0){
            $list['recommendpay'] = 1;
            $list['pay'] = $card['recommend'];
        }

        if($card['recommend_meal']){
            $list['recommendmeal'] = 1;
            $list['meal'] = M('shop_card_meal')->where(array('id'=>array('in',$card['recommend_meal'])))->select();
            foreach($list['meal'] as $k=>$meal){
                $list['meal'][$k]['good'] = M('shop_card_good')->where(array('id'=>array('in',$meal['goods_id']),'status'=>1))->select();
            }
        }
        $this->ajaxReturn($list);
    }
}